package org.abc.fund.service.dataSourceCollection;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.abc.fund.dto.dataSource.JoinQuantResultDTO;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class JoinQuantDataCollectionOrchestratorService {

    private final JoinQuantDataIngestionService ingestionService;
    private final FundDataPersistenceService persistenceService;

    public CollectionResult collectData(String username, String password, Map<String, Object> params) {
        return collectData(username, password, params, true, false);
    }

    public CollectionResult collectData(String username,
                                        String password,
                                        Map<String, Object> params,
                                        boolean persist,
                                        boolean includeRawData) {
        String dataType = (String) params.getOrDefault("data_type", "unknown");
        log.info("开始 JoinQuant 数据采集，数据类型：{}", dataType);

        try {

            JoinQuantResultDTO scriptResult = ingestionService.ingestData(username, password, params);

            if (!"success".equalsIgnoreCase(scriptResult.getStatus())) {
                String errorMsg = "JoinQuant 数据采集脚本执行失败：" + scriptResult.getMessage();
                log.error(errorMsg);
                return CollectionResult.failure(errorMsg);
            }

            log.info("JoinQuant 脚本执行成功：总记录数 {}，已清洗 {}，已剔除 {}",
                    scriptResult.getTotalRecords(),
                    scriptResult.getCleanedRecords(),
                    scriptResult.getRemovedRecords());

            int savedCount = 0;
            if (persist) {

                savedCount = persistenceService.saveData(scriptResult);
                log.info("数据类型 {} 持久化完成，保存记录数 {}", dataType, savedCount);
            }


            int total = scriptResult.getTotalRecords() != null ? scriptResult.getTotalRecords() : 0;
            int cleaned = scriptResult.getCleanedRecords() != null ? scriptResult.getCleanedRecords() : 0;
            int removed = scriptResult.getRemovedRecords() != null ? scriptResult.getRemovedRecords() : 0;

            CollectionResult result = CollectionResult.success(
                    dataType,
                    total,
                    cleaned,
                    removed,
                    savedCount
            );

            if (includeRawData) {
                result.setRawData(scriptResult.getRawData());
            }

            return result;

        } catch (Exception e) {
            log.error("JoinQuant 数据采集流程异常，数据类型 {}：{}", dataType, e.getMessage(), e);
            return CollectionResult.failure("JoinQuant 数据采集失败：" + e.getMessage());
        }
    }


    @lombok.Data
    @lombok.AllArgsConstructor
    @lombok.NoArgsConstructor
    public static class CollectionResult {
        private boolean success;
        private String message;
        private String dataType;
        private Integer totalRecords;
        private Integer cleanedRecords;
        private Integer removedRecords;
        private Integer savedRecords;
        private java.util.List<Map<String, Object>> rawData;

        public static CollectionResult success(String dataType, int totalRecords, int cleanedRecords, int removedRecords, int savedRecords) {
            CollectionResult result = new CollectionResult();
            result.setSuccess(true);
            result.setMessage("数据采集完成");
            result.setDataType(dataType);
            result.setTotalRecords(totalRecords);
            result.setCleanedRecords(cleanedRecords);
            result.setRemovedRecords(removedRecords);
            result.setSavedRecords(savedRecords);
            return result;
        }

        public static CollectionResult failure(String message) {
            CollectionResult result = new CollectionResult();
            result.setSuccess(false);
            result.setMessage(message);
            return result;
        }
    }
}


